const express = require('express');
const router = express.Router();
const pool = require('../config/database');

// 获取所有经销商
router.get('/', async (req, res) => {
  console.log('正在获取经销商列表...查询参数:', req.query);
  const { type } = req.query;
  
  let query = 'SELECT * FROM dealers';
  const params = [];
  
  if (type && ['book', 'goods'].includes(type)) {
    query += ' WHERE type = ?';
    params.push(type);
    console.log('应用类型筛选:', type);
  } else {
    console.log('未应用类型筛选或类型无效');
  }
  
  query += ' ORDER BY id DESC';
  console.log('最终查询:', query);
  console.log('查询参数:', params);
  
  try {
    const [results] = await pool.query(query, params);
    console.log(`找到 ${results.length} 个经销商:`, results);
    res.json(results);
  } catch (err) {
    console.error('获取经销商失败:', err);
    res.status(500).json({ error: err.message });
  }
});

// 添加经销商
router.post('/', async (req, res) => {
  const dealer = req.body;
  console.log('添加新经销商:', dealer);

  if (!dealer.name || !dealer.type) {
    console.error('无效的经销商数据:', dealer);
    res.status(400).json({ error: '经销商名称和类型是必需的' });
    return;
  }

  if (!['book', 'goods'].includes(dealer.type)) {
    console.error('无效的经销商类型:', dealer.type);
    res.status(400).json({ error: '经销商类型必须是 book 或 goods' });
    return;
  }

  try {
    const [result] = await pool.query('INSERT INTO dealers SET ?', dealer);
    console.log('经销商添加成功:', result);
    res.json({ 
      message: '经销商添加成功', 
      id: result.insertId 
    });
  } catch (err) {
    console.error('添加经销商失败:', err);
    res.status(500).json({ error: err.message });
  }
});

// 更新经销商
router.put('/:id', async (req, res) => {
  const dealer = req.body;
  console.log('更新经销商:', req.params.id, dealer);

  try {
    const [result] = await pool.query(
      'UPDATE dealers SET ? WHERE id = ?',
      [dealer, req.params.id]
    );
    
    if (result.affectedRows === 0) {
      console.log('未找到经销商:', req.params.id);
      res.status(404).json({ error: '未找到经销商' });
      return;
    }
    
    console.log('经销商更新成功:', result);
    res.json({ message: '经销商更新成功' });
  } catch (err) {
    console.error('更新经销商失败:', err);
    res.status(500).json({ error: err.message });
  }
});

// 删除经销商
router.delete('/:id', async (req, res) => {
  console.log('删除经销商:', req.params.id);

  try {
    const [result] = await pool.query(
      'DELETE FROM dealers WHERE id = ?',
      [req.params.id]
    );
    
    if (result.affectedRows === 0) {
      console.log('未找到经销商:', req.params.id);
      res.status(404).json({ error: '未找到经销商' });
      return;
    }
    
    console.log('经销商删除成功:', result);
    res.json({ message: '经销商删除成功' });
  } catch (err) {
    console.error('删除经销商失败:', err);
    res.status(500).json({ error: err.message });
  }
});

module.exports = router; 